package com.mayflygeek.mayflyask.framework.webmvc.filter;

import javax.servlet.http.HttpServletRequest;

import com.mayflygeek.mayflyask.framework.util.Strings;
import com.mayflygeek.mayflyask.framework.webmvc.Application;

/**
 * @author 虫虫
 * @team 蜉蝣极客
 * @link www.mayflygeek.com
 * @Emial chongchong@mayflygeek.com
 * 
 */
public final class RequestContexts {
	public static final String REQUEST_CONTEXT_KEY = "requestContext";
	public static final String CONTEXT_PATH_KEY = "ctx";

	private RequestContexts() {

	}

	public static void makeRequestContext(final HttpServletRequest request) {
		// 上下文路径
		request.setAttribute(RequestContexts.CONTEXT_PATH_KEY, request.getContextPath());
		final RequestContext requestContext = new DefaultRequestContext(request);
		request.setAttribute(REQUEST_CONTEXT_KEY, requestContext);
	}

	public static RequestContext currRequestContext() {
		return getAttribute(REQUEST_CONTEXT_KEY);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getAttribute(String key) {
		return (T) getAttribute(Application.getRequest(), key);
	}

	@SuppressWarnings("unchecked")
	public static <T> T getAttribute(HttpServletRequest request, String key) {
		return (T) request.getAttribute(key);
	}

	static class DefaultRequestContext implements RequestContext {
		private final HttpServletRequest request;
		private final String requestURI;

		public DefaultRequestContext(HttpServletRequest request) {
			this.request = request;
			this.requestURI = request.getRequestURI();
		}

		public String getRequestURI() {
			return this.requestURI;
		}

		public String getModulePath() {
			return Strings.takeUntil(Strings.dropHead(getRequestURI(), getContextPath()), '/', 2);
		}

		public String getMenuPath() {
			return Strings.dropHead(getRequestURI(), getContextPath(), getModulePath());
		}

		@Override
		public String getContextPath() {
			return request.getContextPath();
		}
	}
}
